/**
 * User Data Manager
 * Manages user data persistence across all pages using localStorage
 * Stores user responses from various pages and can send them to the backend after Google authentication
 */

const UserDataManager = {
  // Storage key for user survey data
  STORAGE_KEY: 'fluenty_survey_data',

  // Get all stored user data
  getAllData() {
    try {
      const data = localStorage.getItem(this.STORAGE_KEY)
      return data ? JSON.parse(data) : {}
    } catch (error) {
      console.error('Error retrieving user data:', error)
      return {}
    }
  },

  // Save data for a specific page
  savePageData(pageName, data) {
    try {
      const allData = this.getAllData()
      allData[pageName] = {
        ...allData[pageName],
        ...data,
        timestamp: new Date().toISOString(),
      }
      localStorage.setItem(this.STORAGE_KEY, JSON.stringify(allData))
      return true
    } catch (error) {
      console.error('Error saving page data:', error)
      return false
    }
  },

  // Get data for a specific page
  getPageData(pageName) {
    const allData = this.getAllData()
    return allData[pageName] || {}
  },

  // Clear all stored data
  clearAllData() {
    localStorage.removeItem(this.STORAGE_KEY)
  },

  // Send all data to backend
  sendDataToBackend(googleAuthToken) {
    const allData = this.getAllData()

    // Format data in a more structured way
    const formattedData = {
      userInfo: {
        name: allData.yourName ? allData.yourName.name : '',
      },
      surveyResponses: {
        // Question responses
        iDont: allData.iDont ? allData.iDont.selection : null,
        iGet: allData.iGet ? allData.iGet.selection : null,
        iAlways: allData.iAlways ? allData.iAlways.selection : null,
        iUnderstand: allData.iUnderstand ? allData.iUnderstand.selection : null,
        iCanSpeak: allData.iCanSpeak ? allData.iCanSpeak.selection : null,
        iDontHave: allData.iDontHave ? allData.iDontHave.selection : null,
        iStruggle: allData.IStruggle ? allData.IStruggle.selection : null,
        improvementArea: allData.whatArae ? allData.whatArae.selection : null,
        // Add other pages as needed
      },
      preferences: {
        newsletterSubscription: allData.preferences ? allData.preferences.newsletterSubscription : false,
      },
      vocabulary: {
        selectedWords: allData.vocabulary_test ? allData.vocabulary_test.selectedWords : [],
        levelCounts: allData.vocabulary_test ? allData.vocabulary_test.levelCounts : {},
      },
      // Include timestamp
      submittedAt: new Date().toISOString(),
    }

    return fetch('/api/user-survey-data', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${googleAuthToken}`,
      },
      body: JSON.stringify(formattedData),
    })
      .then(response => response.json())
      .then(data => {
        console.log('Data successfully sent to backend:', data)
        return data
      })
      .catch(error => {
        console.error('Error sending data to backend:', error)
        throw error
      })
  },

  // Handle Google authentication redirect with data submission
  handleAuthRedirect() {
    const urlParams = new URLSearchParams(window.location.search)
    if (urlParams.has('auth_success') && urlParams.has('token')) {
      const token = urlParams.get('token')

      // Send all collected data to backend
      this.sendDataToBackend(token)
        .then(() => {
          // Optionally clear data after successful submission
          // this.clearAllData();

          // Redirect to the next page
          const nextPage = urlParams.get('redirect') || 'yourVocabulary.html'
          window.location.href = nextPage
        })
        .catch(error => {
          console.error('Failed to submit survey data:', error)
          // Handle error, maybe retry or show error message
        })

      return true
    }
    return false
  },
}

// Check for redirect parameters on every page load
document.addEventListener('DOMContentLoaded', function () {
  UserDataManager.handleAuthRedirect()
})

// Make UserDataManager globally available
window.UserDataManager = UserDataManager
